package com.yang.o2o.web.shopadmin;

import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yang.o2o.dto.ShopExecution;
import com.yang.o2o.dto.ShopStateEnum;
import com.yang.o2o.entity.Area;
import com.yang.o2o.entity.PersonInfo;
import com.yang.o2o.entity.Shop;
import com.yang.o2o.entity.ShopCategory;
import com.yang.o2o.service.AreaService;
import com.yang.o2o.service.ShopCategoryService;
import com.yang.o2o.service.ShopService;
import com.yang.o2o.util.CodeUtil;
import com.yang.o2o.util.HttpServletRequestUtil;
import com.yang.o2o.util.PathUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;


import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.yang.o2o.util.ImageUtil.getRandomFileName;

@Controller
@RequestMapping("/shopadmin")
public class ShopManagementController {
    @Autowired
    private ShopService shopService;
    @Autowired
    private ShopCategoryService shopCategoryService;
    @Autowired
    private AreaService areaService;
    @RequestMapping(value = "/getshopmanagementInfo",method = RequestMethod.GET)
    @ResponseBody
    private Map<String,Object> getshopmanagementInfo(HttpServletRequest request){
        Map<String,Object> modelMap = new HashMap<String, Object>();
        long shopId = HttpServletRequestUtil.getLong(request,"shopId");
        if(shopId <= 0 ){
            Object currentShopObj = request.getSession().getAttribute("currentShop");
            if(currentShopObj == null ){
                modelMap.put("redirect",true);
                modelMap.put("url","/o2o/shopadmin/shoplist");
            }else{
                Shop currentShop = (Shop) currentShopObj;
                modelMap.put("redirect",false);
                modelMap.put("shopId",currentShop.getShopId());
            }
        }else{
            Shop currentShop = new Shop();
            currentShop.setShopId(shopId);
            request.getSession().setAttribute("currentShop",currentShop);
            modelMap.put("redirect",false);
        }
        return modelMap;
    }

    /**
     * 获取店铺列表*/
    @RequestMapping(value = "/getshoplist",method = RequestMethod.GET)
    @ResponseBody
    private Map<String,Object> getShopList(HttpServletRequest request){
        Map<String,Object> modelMap = new HashMap<String, Object>();
        PersonInfo user = new PersonInfo();
        user.setUserId(1L);
        request.getSession().setAttribute("user",user);
        user = (PersonInfo) request.getSession().getAttribute("user");

      try{
          Shop shopCondition = new Shop();
          shopCondition.setOwner(user);
          ShopExecution se = shopService.getShopList(shopCondition,0,100);

          modelMap.put("shoplist",se.getShopList());
          modelMap.put("user",user);
          modelMap.put("success",true);
      }catch (Exception e){
          modelMap.put("success",false);
          modelMap.put("errMsg",e.getMessage());
      }
        return modelMap;
    }
     /** 更新店铺*/
    @RequestMapping(value = "/updateshop",method = RequestMethod.POST)
    @ResponseBody
    private Map<String,Object> updateShop(HttpServletRequest request){
        Map<String,Object> modelMap = new HashMap<String, Object>();
        //验证码校验
        if(!CodeUtil.checkVerifyCode(request)){
            modelMap.put("success",false);
            modelMap.put("errMsg","验证码错误");
            return modelMap;
        }
        //从Request中获取shop数据
        String shopStr = HttpServletRequestUtil.getString(request,"shopStr");
        //得到Json转换的工具
        ObjectMapper mapper = new ObjectMapper();
        Shop shop = null;
        try {
            shop = mapper.readValue(shopStr,Shop.class);
        }catch (Exception e) {
            modelMap.put("success",false);
            modelMap.put("errMsg",e.getMessage());
            return modelMap;
        }

        //处理图片
        CommonsMultipartFile shopImg = null;
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        if (commonsMultipartResolver.isMultipart(request)){
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
            shopImg = (CommonsMultipartFile) multipartHttpServletRequest.getFile("shopImg");
        }
        //
        if(shop != null && shop.getShopId() != null ){
            ShopExecution se = null;
            try {
                if(shopImg == null){
                    se = shopService.modifyShop(shop,null,null);
                }else{
                    se = shopService.modifyShop(shop,shopImg.getInputStream(),shopImg.getOriginalFilename());
                }

                if(se.getState() == ShopStateEnum.SUCCESS.getState()){
                    modelMap.put("success",true);
                }else{
                    modelMap.put("success",false);
                    modelMap.put("errMsg",se.getStateInfo());
                }
            } catch (IOException e) {
                modelMap.put("success",false);
                modelMap.put("errMsg",se.getStateInfo());
            }
        }else{
            modelMap.put("success",false);
            modelMap.put("errMsg","请输入店铺ID");
        }
        return modelMap;
    }

    /**
     * 获取店铺
     * */
    @RequestMapping(value = "/getshopbyid",method = RequestMethod.GET)
    @ResponseBody
    private Map<String,Object> getShopById(HttpServletRequest request){
        Map<String,Object> modelMap = new HashMap<String, Object>();
        Long shopId = HttpServletRequestUtil.getLong(request,"shopId");
        if(shopId > -1){
       try{
           Shop shop = shopService.getByShopId(shopId);
           List<Area> areaList = areaService.getAreaList();
           modelMap.put("shop",shop);
           modelMap.put("areaList",areaList);
           modelMap.put("success",true);
       }catch (Exception e){
           modelMap.put("success",false);
           modelMap.put("errMsg",e.toString());
       }
        }else{
            modelMap.put("success",false);
            modelMap.put("errMsg","shopId为空");
        }
        return modelMap;
    }
    @RequestMapping(value = "/getshopinitinfo",method = RequestMethod.GET)
    @ResponseBody
    private Map<String,Object> getshopinitinfo(){
    Map<String,Object> modelMap = new HashMap<String, Object>();
    List<ShopCategory> shopCategoryList = new ArrayList<ShopCategory>();
    List<Area> areaList = new ArrayList<Area>();
    try{
        shopCategoryList = shopCategoryService.getShopCategoryList(new ShopCategory());
        areaList = areaService.getAreaList();
        modelMap.put("shopCategoryList",shopCategoryList);
        modelMap.put("areaList",areaList);
        modelMap.put("success",true);
    }catch (Exception e){
        modelMap.put("success",false);
        modelMap.put("errMsg",e.getMessage());
    }
    return modelMap;
    }

    /**
     * 注册店铺
     * */
    @RequestMapping(value = "/registershop",method = RequestMethod.POST)
    @ResponseBody
    private Map<String,Object> registerShop(HttpServletRequest request){
    Map<String,Object> modelMap = new HashMap<String, Object>();
    //验证码校验
    if(!CodeUtil.checkVerifyCode(request)){
        modelMap.put("success",false);
        modelMap.put("errMsg","验证码错误");
        return modelMap;
    }
    //从Request中获取shop数据
    String shopStr = HttpServletRequestUtil.getString(request,"shopStr");
        //得到Json转换的工具
        ObjectMapper mapper = new ObjectMapper();
        Shop shop = null;
        try {
            shop = mapper.readValue(shopStr,Shop.class);
        }catch (Exception e) {
            modelMap.put("success",false);
            modelMap.put("errMsg",e.getMessage());
            return modelMap;
        }


        //处理图片
        CommonsMultipartFile shopImg = null;
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        if (commonsMultipartResolver.isMultipart(request)){
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
               shopImg = (CommonsMultipartFile) multipartHttpServletRequest.getFile("shopImg");
        }else{
            modelMap.put("success",false);
            modelMap.put("errMsg","上传图片不能为空");
        }
        //2.注册店铺
        if(shop != null && shopImg != null){
            PersonInfo owner = (PersonInfo) request.getSession().getAttribute("user");
            shop.setOwner(owner);
            ShopExecution se = null;
            try {
                se = shopService.addShop(shop,shopImg.getInputStream(),shopImg.getOriginalFilename());
                if(se.getState() == ShopStateEnum.CHECK.getState()){
                    modelMap.put("success",true);
                    //该用户可以操作的店铺列表
                    List<Shop> shopList = (List<Shop>)request.getSession().getAttribute("shopList");
                    if(shopList == null || shopList.size() == 0){
                        shopList = new ArrayList<Shop>();
                    }
                    shopList.add(se.getShop());
                    request.getSession().setAttribute("shopList",shopList);
                }else{
                    modelMap.put("success",false);
                    modelMap.put("errMsg",se.getStateInfo());
                }
            } catch (IOException e) {
                modelMap.put("success",false);
                modelMap.put("errMsg",se.getStateInfo());
            }



        }else{
            modelMap.put("success",false);
            modelMap.put("errMsg","请输入店铺信息");
        }
        return modelMap;
    }


    }

